package com.stackfarm.fvcommon.validator;

import com.stackfarm.fvcommon.utils.ValidatorUtils;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class IsNumberValidator implements ConstraintValidator<IsNumber, String> {
    private boolean required = false;

    @Override
    public void initialize(IsNumber constraintAnnotation) {
        required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String v, ConstraintValidatorContext constraintValidatorContext) {
        if (required){
            return ValidatorUtils.isNumber(v);
        }else {
            if (StringUtils.isEmpty(v)){
                return true;
            }else {
                return ValidatorUtils.isNumber(v);
            }
        }
    }
}
